package com.omkarpatil.learningjpa2.mapping.manytomany.uni;

import javax.persistence.EntityManager;

import com.omkarpatil.learningjpa2.util.EntityManagerFactoryFactory;

public class TestDriver {

	public static void main(String[] args) {
		
		EntityManager em1 = EntityManagerFactoryFactory.getEntityManagerFactory().createEntityManager();
		em1.getTransaction().begin();
		
		Post post1 = new Post("grails rocks", "Grails is amazing!!!");
		em1.persist(post1);
		
		Post post2 = new Post("groovy rocks", "Groovy is amazing and it powers grails!!!");
		em1.persist(post2);
		
		Tag tag1 = new Tag("grails");
		tag1.addPost(post1);
		tag1.addPost(post2);
		em1.persist(tag1);
		
		Tag tag2 = new Tag("groovy");
		tag2.addPost(post1);
		tag2.addPost(post2);
		em1.persist(tag2);
		
		em1.getTransaction().commit();
		em1.close();
		
		//Let's see how removing a post from a tag works
		EntityManager em2 = EntityManagerFactoryFactory.getEntityManagerFactory().createEntityManager();
		em2.getTransaction().begin();
		
		Post newPost1 = em2.merge(post1);
		Tag newTag1 = em2.merge(tag1);
		
		newTag1.removePost(newPost1);
		
		System.out.println("##### Numbers of posts for grails tag = " + newTag1.getPosts().size());
		
		em2.remove(newTag1);
		
		em2.getTransaction().commit();
		em2.close();
	}
}
